#!coding:utf-8
'''
Created on Aug 20, 2012

@author: join
''' 
from lottery_jx.common import tools, utils,Constant
from lottery_jx.models import Period, TicketLoan,TicketConstant,SevenColor,ThreeD,FiveBall,SixPlusOne
from django.http import HttpResponse
import xlwt
type_dict4 = {Constant.SingleWay:u'单式', Constant.DoubleWay:u'复式', Constant.BaoHao:u'包号', Constant.HeZhi:u'和值', Constant.DanTuo:u'胆托'}

type_dict = {Constant.SSC:u'时时彩', Constant.SSQ:u'双色球', Constant.QLC:u'七乐彩', Constant.FCD:u'福彩3D', Constant.SXW:u'15选5', Constant.DFL:u'东方6+1'}

@tools.render
def prizelist(request):
    '''返奖明细页面'''

    return 'prize/prizelist.html',{'prize_tb':'prize111'}

_ticketObj={'20':TicketConstant,'01':TicketLoan,'07':SevenColor,'05':ThreeD,'15':FiveBall,'06':SixPlusOne}


@tools.ajaxrender
def prizeDatalist(request):
    '''返奖明细数据'''
    page = int(request.POST.get('page', 1))
    rows = int(request.POST.get('rows', 20))
    query_key = request.POST.get('query_key', None)
    query_value = request.POST.get('query_value', None)
    if not query_key:
        lotterycode='20'
    else:
        lotterycode=query_key
    if not query_value:
        obj = _ticketObj.get(lotterycode)             
        count = obj.objects.filter(deleted=0,prizemoney__isnull=False,prizemoney__gt=0).order_by('-created_at').count()
        datas = obj.objects.filter(deleted=0,prizemoney__isnull=False,prizemoney__gt=0).order_by('-created_at')[(page-1)*rows: page*rows] 
    else:
        period0=Period.objects.filter(deleted=False,periodid=query_value).all()
        if period0:
            obj = _ticketObj.get(lotterycode)
            count = obj.objects.filter(deleted=0,tradeId__period=period0[0],prizemoney__isnull=False,prizemoney__gt=0).order_by('-created_at').count()
            datas = obj.objects.filter(deleted=0,tradeId__period=period0[0],prizemoney__isnull=False,prizemoney__gt=0).order_by('-created_at')[(page-1)*rows: page*rows]
    try:
        if datas:
            data_list = []
            for data in datas:                   
                if not data.prizemoney:
                    data.prizemoney=float(0) 
#                if not utils.convert_datetime_to_str(data.prizetime,"%Y-%m-%d %H:%M:%S") or utils.convert_datetime_to_str(data.prizetime,"%Y-%m-%d %H:%M:%S") == 'None':
                if not data.prizetime:
                    prizetime = "暂未兑奖"
                else:
                    prizetime = utils.convert_datetime_to_str(data.prizetime,"%Y-%m-%d %H:%M:%S")
                if not data.tradeId.prizeaccount or data.tradeId.prizeaccount == 'None':
                    add = "暂无"
                else:
                    add = data.tradeId.prizeaccount.address
                data_list.append({'typecode': type_dict.get(str(lotterycode)),
                                  'lotteryperiod': data.tradeId.period.periodid,
                                  'lotteryNumber1': type_dict4.get(int(data.lotteryNumber.split(':')[2])),
                                  'lotteryNumber2': data.lotteryNumber.split(':')[3],
                                  'lotteryNumber': data.lotteryNumber.split(':')[0],
                                    'ticketamount': data.ticketamount,
                                    'Validitytime': utils.convert_datetime_to_str(data.validitytime,"%Y-%m-%d %H:%M:%S"),
#                                    'Validitytime': Validitytime,
                                    
                                    'buytime': utils.convert_datetime_to_str(data.buytime,"%Y-%m-%d %H:%M:%S"),
                                    'buyaddress':data.tradeId.accountid.address,
                                    'prizeaddress':add,
                                 
                                    'prizetime': prizetime,
                                    'prizemoney':data.prizemoney
#                                     'totalprizemoney':data.prizemoney*data.ticketamount
                                    })
            values = {'total':count,
                      'rows': data_list,
                    }
            return values
        else:
            return None
    except Exception as e:
        print str(e)
        return None  
    
def export_awards(request):
    '''导出返奖记录到excel'''
    response = HttpResponse(mimetype="application/ms-excel")
    response['Content-Disposition'] = 'attachment; filename=prizeinfo_report.xls'
    wb = xlwt.Workbook()
    sheet_name = 'prizeinfo'
    ws = wb.add_sheet(sheet_name)
    
    from xlwt import Font,Borders,Alignment,XFStyle
    fnt = Font()
    fnt.name = 'Arial'
    fnt.colour_index = 0
    fnt.bold = True
    
    borders = Borders()
    borders.left = 1
    borders.right = 1
    borders.top = 1
    borders.bottom = 1
    
    al = Alignment()
    al.horz = Alignment.HORZ_CENTER
    al.vert = Alignment.VERT_CENTER
    style = XFStyle()
    style.font = fnt
    style.alignment = al
    style2 = XFStyle()
    style2.alignment = al
    
    datas1 = TicketLoan.objects.filter(deleted=0,prizemoney__isnull=False,prizemoney__gt=0).order_by('-created_at')
    datas2 = TicketConstant.objects.filter(deleted=0,prizemoney__isnull=False,prizemoney__gt=0).order_by('-created_at')
    datas3 = SevenColor.objects.filter(deleted=0,prizemoney__isnull=False,prizemoney__gt=0).order_by('-created_at')
    datas4 = ThreeD.objects.filter(deleted=0,prizemoney__isnull=False,prizemoney__gt=0).order_by('-created_at')
    datas5 = FiveBall.objects.filter(deleted=0,prizemoney__isnull=False,prizemoney__gt=0).order_by('-created_at')
    datas6 = SixPlusOne.objects.filter(deleted=0,prizemoney__isnull=False,prizemoney__gt=0).order_by('-created_at')
    datass = [(datas1,'01'),(datas2,'20'),(datas3,'07'),(datas4,'05'),(datas5,'15'),(datas6,'06')]
    ws.write(0, 0, 'No.',style)
    ws.write(0, 1, u'期次',style)
    ws.write(0, 2, u'彩票类型',style)
    ws.write(0, 3, u'购买时间',style)
    ws.write(0, 4, u'购买地点',style)
    ws.write(0, 5, u'中奖金额',style)
    ws.write(0, 6, u'兑奖时间',style)
    
    rownum = 1
    for datas in datass:
        lotterycode = datas[1]
        for data in datas[0]:
            if not data.prizetime:
                prizetime = u"暂未兑奖"
            else:
                prizetime = utils.convert_datetime_to_str(data.prizetime,"%Y-%m-%d %H:%M:%S")
    #        
            ws.write(rownum,0,rownum,style2)
            ws.write(rownum,1,data.tradeId.period.periodid,style2)
            ws.write(rownum,2,type_dict.get(lotterycode),style2)
            ws.write(rownum,3,utils.convert_datetime_to_str(data.buytime,"%Y-%m-%d %H:%M:%S"),style2)
            ws.write(rownum,4,data.tradeId.accountid.address,style2)
            ws.write(rownum,5,data.prizemoney,style2)
            ws.write(rownum,6,prizetime,style2)
            rownum += 1
                
    wb.save(response)
    return response